<template>
	<view class="container">
		<view class="v-qianggou">
			<view class="v-bottom">
				<view class="v-op-qianggou" v-if="datas.IsAM" @click="qiangGou">
					<view class="v-op-qianggou-outter">
						<view class="v-op-qianggou-inner">
							<view class="">立即</view>
							<view class="">抢购</view>
						</view>
					</view>
				</view>
				<view class="v-daojishi" v-if="!datas.StartQiangGou">
					<text class="t-daojishi">{{ datas.TimeRemaining }}</text>
					<text>距离下次抢购还剩</text>
				</view>
			</view>
			<view class="v-top">
				<view class="v-top-left">
					<view class="v-title-1">上午专场</view>
					<view class="v-title-2">
						抢购时间：{{`${datas.SysQiangGouTime_HourStart.padStart(2, '0')}:${datas.SysQiangGouTime_MinuteStart.padStart(2, '0')} ~ ${datas.SysQiangGouTime_HourEnd.padStart(2, '0')}:${datas.SysQiangGouTime_MinuteEnd.padStart(2, '0')}`}}
					</view>
				</view>
				<view class="v-top-right">
					<view class="v-huiyuan" :class="datas.CurUser.IsVIP !== '1' ? 'v-huiyuan-active' : ''"
						@click="gradeVIP">开通会员</view>
				</view>
			</view>
		</view>
		<uni-popup ref="message" type="message" class="pop-msg">
			<uni-popup-message :type="msgType" :message="messageText" :duration="duration"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import {
		dateUtils,
		authTokenUtil,
		validLoginToken
	} from "../../common/util.js"
	export default {
		data() {
			return {
				messageText: '',
				msgType: 'success',
				duration: 2000,

				datas: {
					HasAddress: false,
					IsAM: false,
					CurUser: null,
					SysQiangGouTime_HourStart: 10,
					SysQiangGouTime_MinuteStart: 30,
					SysQiangGouTime_HourEnd: 10,
					SysQiangGouTime_MinuteEnd: 40,
					TimeRemaining: ' --:--:--',
					StartQiangGou: true,
					Timer: null
				}
			};
		},
		methods: {

			formatTimeRemaining: function(currentTime, specifiedTime) {
				// 创建Date对象
				let current = new Date(currentTime);
				let specified = new Date(specifiedTime);

				// 计算时间戳差值（毫秒）
				let diff = specified - current;

				// 将时间戳差值转换为总秒数
				let totalSeconds = Math.floor(diff / 1000);
				let totalMinutes = Math.floor(totalSeconds / 60);
				let totalHours = Math.floor(totalMinutes / 60);

				// 计算剩余的秒数和分钟数
				let remainingSeconds = totalSeconds % 60;
				let remainingMinutes = totalMinutes % 60;

				// 格式化输出结果
				let hours = totalHours.toString().padStart(2, '0');
				let minutes = remainingMinutes.toString().padStart(2, '0');
				let seconds = remainingSeconds.toString().padStart(2, '0');

				// return `${hours} 小时 ${minutes} 分钟 ${seconds} 秒`;
				return `${hours}:${minutes}:${seconds}`;
			},
			async checkIsAM() {
				let _this = this;
				// 创建当前时间的Date对象
				let nowres = await _this.getServerTime();
				let now = new Date(nowres);
				console.log(now, 99992)
				let today_Start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
				let today_End = new Date(now.getFullYear(), now.getMonth(), now.getDate(), _this.datas
					.SysQiangGouTime_HourEnd, _this.datas.SysQiangGouTime_MinuteEnd, 0);
				if (now >= today_Start && now <= today_End) {
					_this.datas.IsAM = true;
				} else {
					_this.datas.IsAM = false;
				}
			},
			async getNextQiangGouTime() {
				let _this = this;
				// 创建当前时间的Date对象
				let nowres = await _this.getServerTime();
				let now = new Date(nowres);
				console.log(now, 99991)
				let today_Start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), _this.datas
					.SysQiangGouTime_HourStart, _this.datas.SysQiangGouTime_MinuteStart, 0);
				let today_End = new Date(now.getFullYear(), now.getMonth(), now.getDate(), _this.datas
					.SysQiangGouTime_HourEnd, _this.datas.SysQiangGouTime_MinuteEnd, 0);
				let nextQiangGouTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, _this.datas
					.SysQiangGouTime_HourStart, _this.datas.SysQiangGouTime_MinuteStart, 0);

				// 获取三天时间的毫秒数
				const threeDays = 3 * 24 * 60 * 60 * 1000;
				if (_this.datas.CurUser && _this.datas.CurUser.IsVIP && _this.datas.CurUser.ApplyVIPTime) {

					if (now.getTime() - new Date(_this.datas.CurUser.ApplyVIPTime).getTime() < threeDays) {
						today_Start.setMinutes(today_Start.getMinutes() - 1);
					}

				}

				if (now < today_Start || now >= today_Start && now < today_End) {
					return today_Start;
				}
				return nextQiangGouTime;
			},
			loadAddress: function() {
				console.log('loadAddress');

				let _this = this;
				//正式代码
				var authToken = authTokenUtil();
				var queryData = {
					PageSize: 1,
					PageIndex: 1,
					QueryContent: ""
				};
				uni.request({
					url: _this.sysInfo.BasePath + 'Address/GetAddressDatas',
					method: 'POST',
					data: queryData,
					header: {
						'content-type': 'application/json',
						Authorization: `${authToken}`
					},
					success: (res) => {
						if (res && res.data && res.data.Succeeded === true) {
							console.log(res);
							_this.datas.HasAddress = res.data.Data.Datas.length > 0
						} else {
							_this.sysUtils.tip({
								sender: _this,

								title: '加载地址信息失败！',
								icon: 'error'
							});
						}
					},
					fail: () => {
						_this.sysUtils.tip({
							sender: _this,
							title: '加载地址信息失败！',
							icon: 'error'
						});
					},
					complete: () => {}
				});
				uni.stopPullDownRefresh();
				if (_this.datas.currentPage >= _this.datas.totalPage) {
					_this.datas.loadStatus = 'noMore';
				} else {
					_this.datas.loadStatus = 'more';
				}
			},

			qiangGou: function() {
				let _this = this;

				if (!_this.datas.HasAddress) {
					_this.sysUtils.tip({
						sender: _this,
						title: '请先维护地址信息！',
						icon: 'error'
					});
				} else {
					uni.navigateTo({
						url: '/pages/rush-purchase/detail'
					});
				}
			},
			loadSysQiangGouTime: function(callback) {

				let _this = this;
				//正式代码
				var authToken = authTokenUtil();

				uni.request({
					url: _this.sysInfo.BasePath + 'RushPurchase/GetSettings',
					method: 'POST',
					data: null,
					header: {
						'content-type': 'application/json',
						'Authorization': `${authToken}`
					},
					success: (res) => {
						if (res && res.data && res.data.Succeeded === true) {
							console.log(res)
							_this.datas.SysQiangGouTime_HourStart = res.data.Data
								.SysQiangGouTime_HourStart;
							_this.datas.SysQiangGouTime_MinuteStart = res.data.Data
								.SysQiangGouTime_MinuteStart;
							_this.datas.SysQiangGouTime_HourEnd = res.data.Data.SysQiangGouTime_HourEnd;
							_this.datas.SysQiangGouTime_MinuteEnd = res.data.Data
								.SysQiangGouTime_MinuteEnd;

							callback();

						} else {
							_this.sysUtils.tip({
								sender: _this,

								title: '加载抢购时间设置失败！',
								icon: 'error'
							});
						}
					},
					fail: () => {
						_this.sysUtils.tip({
							sender: _this,
							title: '加载抢购时间设置失败！',
							icon: 'error'
						});
					},
					complete: () => {}
				});
			},
			getServerTime: function(callback) {
				let _this = this;
				//正式代码
				var authToken = authTokenUtil();

				return new Promise((resolve, reject) => {
					uni.request({
						url: _this.sysInfo.BasePath + 'Sys/GetSystemTime',
						method: 'POST',
						data: null,
						header: {
							'content-type': 'application/json',
							'Authorization': `${authToken}`
						},
						success: (res) => {
							if (res && res.data && res.data.Succeeded === true) {
								console.log(res)
								// 请求成功处理
								resolve(res.data.Data);
							} else {
								// 请求失败处理
								reject('获取服务器时间失败！');
							}
						},
						fail: () => {
							// 请求失败处理
							reject('获取服务器时间失败！');
						},
						complete: () => {}
					});
				});
			},
			gradeVIP: function() {
				let _this = this;
				//正式代码
				var authToken = authTokenUtil();
				_this.datas.CurUser.IsVIP = "1";
				uni.request({
					url: _this.sysInfo.BasePath + 'RushPurchase/GradeVIP',
					method: 'POST',
					data: _this.datas.CurUser,
					header: {
						'content-type': 'application/json',
						'Authorization': `${authToken}`
					},
					success: (res) => {
						if (res && res.data && res.data.Succeeded === true) {
							console.log(res)
							uni.setStorage({
								key: 'CurrentUser',
								data: res.data.Data
							});

						} else {
							_this.sysUtils.tip({
								sender: _this,

								title: '开通会员失败！',
								icon: 'error'
							});
						}
					},
					fail: () => {
						_this.sysUtils.tip({
							sender: _this,
							title: '开通会员失败！',
							icon: 'error'
						});
					},
					complete: () => {}
				});
			},
			init: function() {
				let _this = this;
				console.log('init');
				_this.datas.StartQiangGou = false;
				if (_this.Timer) {
					clearInterval(_this.Timer);
				}



				uni.getStorage({
					key: 'CurrentUser',
					success: (res) => {
						console.log(res);
						_this.datas.CurUser = res.data;
					}
				});

				_this.loadAddress();

				// //测试代码开始
				// _this.datas.StartQiangGou = true;
				// return;
				// //测试代码结束

				//正式代码
				_this.loadSysQiangGouTime(() => {
					_this.Timer = setInterval(async () => {
						await _this.checkIsAM();

						let curTime = await _this.getServerTime();
						console.log(curTime, 999999)
						let nextQiangGouTime =await _this.getNextQiangGouTime();
						let current = new Date(curTime);
						let specified = new Date(nextQiangGouTime);

						// 计算时间戳差值（毫秒）
						let diff = specified - current;
						if (diff <= 0) {
							_this.datas.StartQiangGou = true;
							clearInterval(_this.Timer);
							return;
						}
						_this.datas.TimeRemaining = _this.formatTimeRemaining(curTime,
							nextQiangGouTime);
					}, 1000);

				});

			}
		},
		onShow() {
			let _this = this;
			_this.init();
		},
		created() {
			let _this = this;
			validLoginToken(null, () => {
				uni.reLaunch({
					url: "/pages/account/login"
				})
			})
			// _this.init();
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		justify-content: stretch;
		align-items: stretch;
		height: 100%;
		position: fixed;
		background-image: url('../../static/qiangou.png');
		background-repeat: no-repeat;
		background-position: center;
		background-size: cover;
		width: 100%;
	}

	.v-qianggou {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: stretch;
		/* background: linear-gradient(215deg, #c93a00ff, #eab55eff); */
		height: 100%;
		color: #fff;
		box-sizing: border-box;
		padding: 50rpx;
	}

	.v-top {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		flex: 2;
	}

	.v-top-left {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: stretch;
		flex: 1;
		box-sizing: border-box;
		padding-left: 10rpx;
	}

	.v-title-1 {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		font-size: 56rpx;
		letter-spacing: 1px;
		font-weight: bold;
	}

	.v-title-2 {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		font-size: 32rpx;
		letter-spacing: 1px;
		font-weight: bold;
		margin-top: 20rpx;
	}

	.v-top-right {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: stretch;
		width: 180rpx;
	}

	.v-huiyuan {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 70rpx;
		width: 180rpx;
		border-radius: 40rpx;
		border: 1rpx solid #a3a3a3;
		background-color: #a3a3a3;
		font-size: 26rpx;
	}

	.v-huiyuan-active {
		border: 1rpx solid #fff;
		background: linear-gradient(15deg, #dd1f38, #f7e34d);
	}

	.v-bottom {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		flex: 3;
		box-sizing: border-box;
		letter-spacing: 2rpx;
	}

	.v-daojishi {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
	}

	.v-daojishi text {
		font-size: 32rpx;
		font-weight: bold;
		margin-top: 20rpx;
	}

	.t-daojishi {
		font-size: 72rpx !important;
		font-weight: bold;
	}

	.v-op-qianggou {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		cursor: pointer;
		flex: 1;
	}

	.v-op-qianggou text {
		font-size: 32rpx;
		font-weight: bold;
		margin-top: 20rpx;
	}

	.img-qianggou {
		height: 360rpx;
		width: 360rpx;
	}

	.v-op-qianggou-outter {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 360rpx;
		width: 360rpx;
		background-color: #ffcbe3;
		border-radius: 50%;
		margin-top: 22%;
	}

	.v-op-qianggou-inner {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 320rpx;
		width: 320rpx;
		background: linear-gradient(135deg, #fbf083, #f90046);
		border-radius: 50%;
		font-size: 56rpx;
		font-weight: bold;
	}
</style>